<template>
  <div class="attachment-resume">
    <div class="header">
      <div class="title">附件简历管理</div>
      <div class="add-box" @click="uploadResume">
        <img :src="blueAdd" class="icon" alt="添加简历" />
        <span class="text">添加</span>
      </div>
    </div>
    <div class="resume-list">
      <el-scrollbar style="height: 100%" v-if="resumeList.length">
        <div class="resume-list-item" v-for="item in resumeList" :key="item.id">
          <img :src="resumeIcon" class="resumeIcon" alt="简历" />
          <div class="resume-name">
            <div class="name" :title="item.attName">
              {{ item.attName }}
            </div>
            <div class="time">{{ item.createTime }} 上传</div>
          </div>
          <el-dropdown @command="(e) => handleCommand(e, item)" class="dropdown">
            <img :src="columnMore" class="columnMore" />
            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item command="a">预览</el-dropdown-item> -->
              <el-dropdown-item command="b">下载</el-dropdown-item>
              <el-dropdown-item command="c">重命名</el-dropdown-item>
              <el-dropdown-item command="d">简历解析</el-dropdown-item>
              <!-- <el-dropdown-item command="e">优先展示给HR看</el-dropdown-item> -->
              <el-dropdown-item command="f">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-scrollbar>
      <el-empty class="empty" description="暂无简历附件" v-else></el-empty>
    </div>
    <el-upload @click.stop v-show="false" class="upload-file" :multiple="false" id="uploadFile" :action="uploadAction"
      :accept="accept" :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload">
    </el-upload>
    <RenameDialog :visible.sync="visibleRename" :file="currentFile" @confirm="handleRenameConfirm"></RenameDialog>
    <FullLoading v-if="showFullLoading" text="解析中..."></FullLoading>
  </div>
</template>

<script>
// import VueOfficePdf from "@vue-office/pdf";
// import VueOfficeDocx from "@vue-office/docx";
import {
  attachmentList,
  updateResumeName,
  removeResume,
  addResume,
  previewResume,
  analysisResult,
  dealAnalysisResume,
} from "@/api/mine";
import { download } from "@/utils/fileSaver";
import blueAdd from "@/assets/images/png/blueAdd.png";
import resumeIcon from "@/assets/images/png/resumeIcon.png";
import columnMore from "@/assets/images/png/columnMore.png";
import RenameDialog from "./components/RenameDialog";
import FullLoading from "@/components/FullLoading";
export default {
  components: {
    // VueOfficePdf,
    // VueOfficeDocx,
    RenameDialog,
    FullLoading,
  },
  data() {
    return {
      blueAdd,
      resumeIcon,
      columnMore,
      uploadAction: "https://upload.yl1001.com/upload/files/save",
      accept: ".pdf,.docx",
      visibleRename: false,
      showFullLoading: false,
      currentFile: {},
      resumeList: [],
      MAX_RETRY_TIMES: 10,
      retryCount: 0,
      resumeHasAnalysis: false,
      timer: null,
      personId: localStorage.getItem("personId"),
    };
  },
  created() {
    this.attachmentListFn();
  },
  mounted() {
    this.$bus.$on("uploadResume", this.uploadResume);
    this.$bus.$on("refreshResumeList", this.attachmentListFn);
  },
  beforeMount() {
    this.$bus.$off("uploadResume");
    this.$bus.$off("refreshResumeList");
  },
  methods: {
    async attachmentListFn() {
      const params = {
        personId: this.personId,
        attStatus: "1",
      };
      const res = await attachmentList(params);
      if (res.code === 200) {
        this.resumeList = res.data;
      }
    },
    beforeUpload(files) {
      this.fileName = files.name;
      if (
        [
          "application/pdf",
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "application/vnd.ms-powerpoint",
        ].indexOf(files.type) == -1
      ) {
        this.$message.error("请上传正确的文本格式文件，如pdf doc docx");
        return false;
      }
    },
    async handleUploadSuccess(data) {
      console.log(data);
      const fileUrl = data.data[0];
      const params = {
        personId: this.personId,
        attName: this.fileName,
        attUrl: fileUrl,
      };
      const res = await addResume(params);
      if (res.code === 200) {
        // 有可能是简历列表弹窗调用的上传功能，所以通过bus事件通知弹窗更新列表
        this.$bus.$emit("resumeUploadSuccess");
        this.$message.success("简历添加成功");
        this.attachmentListFn();
      }
    },
    uploadResume() {
      if (this.resumeList.length >= 3) {
        this.$message.warning(
          "只可以导入3个附件简历，若想换文件，请先删除现有附件"
        );
        return;
      }
      document.querySelector("#uploadFile").querySelector("input").click();
    },
    handleDownload(item) {
      download(item.attUrl, item.attName); // TODO:
    },
    handleRename(item) {
      this.currentFile = item;
      this.visibleRename = true;
    },
    async handleRenameConfirm(val) {
      const params = {
        id: this.currentFile.id,
        attName: val,
      };
      const res = await updateResumeName(params);
      if (res.code === 200) {
        this.$message.success("重命名成功");
        this.visibleRename = false;
        this.attachmentListFn();
      }
    },
    // 简历在线解析
    async handleResumeParse(item) {
      this.$confirm("使用简历解析会覆盖原有简历，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(async () => {
        this.currentFile = item;
        this.showFullLoading = true;
        const params = {
          personId: this.personId,
          fileUrl: item.attUrl,
        };
        const res = await dealAnalysisResume(params);
        if (res.code == 200) {
          setTimeout(() => {
            this.startRequest();
          }, 1000);
        } else {
          this.showFullLoading = false;
          this.$message.error("简历解析失败，请稍后再试");
        }
      });
    },
    // 获取附件简历解析结果状态
    async analysisResultFn() {
      try {
        const res = await analysisResult({
          personId: this.personId,
          fileUrl: this.currentFile.attUrl,
          retryNum: this.retryCount + 1,
        });
        if (res.code === 200) {
          const status = res.data;
          if (status == 0) {
            this.$message.error("没有要解析的简历");
            this.endRequest();
          } else if (status == 1) {
            this.showFullLoading = true; // 显示全屏loading，这句不要也行
          } else if (status == 2) {
            this.$message.error("简历解析失败，请重试");
            this.endRequest();
          } else if (status == 3) {
            this.resumeHasAnalysis = true;
            this.endRequest();
            this.$message.success("简历解析成功");
            this.$emit("reqGetResumeData");
          } else {
            this.$message.error("未知错误");
            this.endRequest();
          }
        } else {
          this.endRequest();
          this.$message.error(res.status_desc);
        }
      } catch (err) {
        this.endRequest();
        this.$message.error(err.status_desc);
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且仍然未解析完成
      if (!this.resumeHasAnalysis && this.retryCount >= this.MAX_RETRY_TIMES) {
        this.$message.error(
          "超过最大重试次数，简历仍在解析中，请稍后重新进来此页面"
        );
        this.endRequest();
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.analysisResultFn();
        } else {
          clearInterval(this.timer);
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.retryCount = 0;
      this.showFullLoading = false;
      this.timer = null;
    },
    handleDelete(item) {
      this.$confirm("确定删除此简历?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            id: item.id,
            attStatus: "2",
          };
          const res = await removeResume(params);
          if (res.code === 200) {
            this.attachmentListFn();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {});
    },
    handleCommand(e, item) {
      switch (e) {
        case "b":
          this.handleDownload(item);
          break;
        case "c":
          this.handleRename(item);
          break;
        case "d":
          this.handleResumeParse(item);
          break;
        case "f":
          this.handleDelete(item);
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dropdown-menu {
  border-radius: 8px;
}
.attachment-resume {
  height: 100%;
  min-width: 250px;
  .header {
    display: flex;
    justify-content: space-between;
    padding: 20px 18px 16px 18px;
    .title {
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 20px;
      color: #333333;
    }
    .add-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .icon {
        width: 20px;
        height: 20px;
        margin-right: 2px;
      }
      .text {
        color: #4880ff;
        cursor: pointer;
        font-size: 14px;
      }
    }
  }
  .resume-list {
    height: calc(100% - 59px);
    padding: 0 0 6px 14px;
    &-item {
      display: flex;
      align-items: center;
      padding: 15px 16px 15px 0;
      &:last-child {
        margin-bottom: 0;
      }
      .resumeIcon {
        width: 34px;
        height: 34px;
        margin-right: 13px;
      }
      .resume-name {
        .name {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #222222;
          margin-bottom: 5px;
          width: 132px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .time {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #bfbfbf;
      }
    }
    .dropdown {
      margin-left: auto;
      .columnMore {
        width: 20px;
        height: 20px;
        margin-left: auto;
        cursor: pointer;
      }
    }
  }
}
</style>
